package com.springsecurity.handler;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义 403 无权限处理器(handler)
 */
@Configuration
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);//403 无权限
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out =httpServletResponse.getWriter();
        out.print("\"status\":\"error\",\"msg\":\"权限不足,请联系管理员\"");
        out.flush();
        out.close();
    }
}
